package com.moore.Servlet;

import com.alibaba.fastjson2.JSON;
import com.moore.net.HttpRequest;
import com.moore.net.HttpResponse;
import com.moore.net.HttpServlet;
import com.moore.utils.UserUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class UserForAdminServlet extends HttpServlet {
    @Override
    public byte[] doGet(HttpRequest request, HttpResponse response) {
        byte[] responseData = new byte[2048];
        String type = request.getParams().get("type");
        switch (type) {
            case "get":
                responseData = JSON.toJSONString(UserUtils.getAllUsers()).getBytes();
                break;
            case "delete": {
                String id = request.getParams().get("userId");
                responseData = UserUtils.deleteUser(id).getBytes();
                break;
            }
            case "update": {
                String id = request.getParams().get("userId");
                String key = request.getParams().get("key");
                String value;
                try {
                    value = URLDecoder.decode(request.getParams().get("value"),"utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                responseData = UserUtils.update(key, value, id).getBytes();
                break;
            }
            case "add":
                RegServlet regServlet = new RegServlet();
                responseData = regServlet.doGet(request, response);
                break;
        }
        return responseData;
    }
}
